<?php

namespace App\Services\Assess;

use App\Helpers\JwtUtils;
use App\Models\Account\UserAccountModel;
use App\Models\Assess\EmailTemplateModel;
use App\Models\Assess\EmailTemplateSkuModel;
use App\Models\UserModel;
use App\Services\BaseService;
use App\Services\Common\CommonService;
use App\Services\Common\RedisService;
use Illuminate\Support\Facades\Log;

class EmailTemplateService extends BaseService
{
    //模板类型 页面展示的样式 1:注册用户-已激活,2:选择礼品但未留评用户,3:中低评分用户,4:高评分用户,5:高评价已匹配用户,6:高评价未匹配用户,7:中差评用户,8:好评用户,9:激活失败用户,10:激活异常用户
    public $templateTypeHtml = [
        1=>'default',
        2=>'success',
        3=>'info',
        4=>'success',
        5=>'success',
        6=>'danger',
        7=>'danger',
        8=>'default',
        9=>'info',
        10=>'danger',
    ];

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new EmailTemplateModel();
    }

    public function getList()
    {
        $param = request()->all();
        // 查询条件
        $map[] = ['mark','=',1];
        $name = getter($param, 'name', '');
        $templateType = getter($param, 'template_type', '');
        $createUser = getter($param, 'create_user', '');
        $sort = getter($param, 'sort', 'create_time');
        $order = getter($param, 'order', 'desc');
        $time = getter($param, 'time', []);
        $page_size = getter($param, 'page', 1);
        $limit = getter($param, 'limit', 10);
        if (!empty($time)) {
            if (!empty($time[0])) $map[] = ['m.create_time', '>=', strtotime($time[0])];
            if (!empty($time[1])) $map[] = ['m.create_time', '<=', strtotime($time[1])];
        }
        if (!empty($name))  $map[] = ['m.name', 'like', "%{$name}%"];
        if (!empty($templateType))  $map[] = ['m.type', '=', $templateType];
        if (!empty($createUser))  $map[] = ['m.create_user', '=', $createUser];

        //权限过滤
//        $createUserList = CommonService::userAuth();
        $skuAuthList = CommonService::skuAuth();

        $mainTable = $this->model->getTable();
        $EmailTemplateSkuModel = new EmailTemplateSkuModel();
        $sonTable = $EmailTemplateSkuModel->getTable();
        $model = $this->model::from("$mainTable as m")
            ->select('m.*')
            ->leftJoin("$sonTable as s", 's.email_template_id', '=', 'm.id')
            ->distinct(true)
            ->where($map);
        $model2 = $this->model::from("$mainTable as m")
            ->select('m.id')
            ->leftJoin("$sonTable as s", 'm.id', '=', 's.email_template_id')
            ->distinct('m.id')
            ->where($map);

        $offset = ($page_size - 1) * $limit;
        if (!empty($skuAuthList)){
            $model2->whereIn('s.sku',$skuAuthList);
            $model->whereIn('s.sku',$skuAuthList);
        }

        $list = $model
            ->orderBy($sort, $order)
            ->offset($offset)
            ->limit(PERPAGE)
            ->get()->toArray();
        $count = $model2->count();


        $skuArr = [];
        if (!empty($list)){
            $ids = array_column($list,'id');
            $EmailTemplateSkuModel = new EmailTemplateSkuModel();
            $skuList = $EmailTemplateSkuModel->whereIn('email_template_id',$ids)->get()->toArray();
            foreach ($skuList as $skuV){
                $skuArr[$skuV['email_template_id']][] = $skuV['sku'];
            }
        }

        foreach ($list as $key=>$val){

            $info = $this->model->getInfo($val['id']);
            if (!$info) {
                continue;
            }

            $val['type_tag'] = $this->templateTypeHtml[$val['type']] ?? '';
            $val['type_tag_html'] = $this->model->userType[$val['type']] ?? '';
            if (!empty($skuArr[$val['id']])){
                $val['sku_list'] = implode(';',$skuArr[$val['id']]);
            }
            $val = array_merge($val,$info);
            $list[$key] = $val;
        }

        return array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list,
            "count" => $count,
        );

    }


    /**
     * @Notes:添加或编辑
     * @Interface edit
     * @return array|void
     * @author: wuyu
     * @Time: 2023/5/8   16:45
     */
    public function edit()
    {
        try {
            $params = request()->all();
            $id = $params['id'] ?? 0;
            $type = $params['type'] ?? 1;
            $name = $params['name'] ?? '';
            $skuList = $params['sku_list'] ?? '';
            $title = $params['title'] ?? '';
            $content = $params['content'] ?? '';

            if (empty($type)) throw new \Exception('模板类型不能为空');
            if (empty($name)) throw new \Exception('模板名称不能为空');
            if (empty($title)) throw new \Exception('邮件标题不能为空');
            if (empty($content)) throw new \Exception('邮件内容不能为空');
            if (empty($skuList)) throw new \Exception('sku不能为空');

            $content = urldecode($content);
            $title = urldecode($title);
            $skuList = str_replace(['；', ',', '，',"\r\n", "\r", "\n"], ';', $skuList);
            $skuArr = explode(';',$skuList);

            $data = [
                'type' => $type,
                'name' => $name,
                'title' => $title,
                'content' => $content
            ];
            if (empty($id)) {
                $data['create_user'] = $this->model->userId;
                $data['create_time'] = $data['update_time'] = time();
                $exists = $this->model->where('name', '=', $name)->where('mark', '=', 1)->count();
            } else {
                $data['update_user'] = $this->model->userId;
                $data['update_time'] = time();
                $exists = $this->model->where('name', '=', $name)->where("id", "<>", $id)->where('mark', '=', 1)->count();
            }
            if ($exists > 0) throw new \Exception('模板名称已存在,请勿重复添加');

            if (empty($id)) {
                $insertId = $this->model->insertGetId($data);
            } else {
                $this->model->where('id', '=', $id)->update($data);
                $insertId = $id;
                $this->model->cacheReset($id, $data, $id);
            }
            if (empty($insertId)) throw new \Exception('操作失败');

            $EmailTemplateSkuModel = new EmailTemplateSkuModel();
            $EmailTemplateSkuModel->where('email_template_id','=',$insertId)->delete();
            foreach ($skuArr as $sku){
                $skuData = [
                    'email_template_id'=>$insertId,
                    'sku'=>$sku
                ];
                $EmailTemplateSkuModel->insert($skuData);
            }
            return message("保存成功", true, []);

        } catch (\Exception $e) {
            return message("保存失败:" . $e->getMessage(), false, []);
        }
    }


    public function getEmailTemplateConfig()
    {

        $config = [];
        //获取用户信息
        $userData = RedisService::getUserList();
        $EmailTemplateModel = new EmailTemplateModel();
        $config['user_list'] = $userData;
        $config['template_type_list'] = $EmailTemplateModel->userType;

        return message("操作成功", true, $config);
    }


}
